package com.sz.admin.dtuinfo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.RequiredArgsConstructor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import com.sz.core.common.entity.ApiPageResult;
import com.sz.core.common.entity.ApiResult;
import com.sz.core.common.constant.GlobalConstant;
import com.sz.core.common.entity.PageResult;
import com.sz.core.common.entity.SelectIdsDTO;
import com.sz.admin.dtuinfo.service.DtuInfoService;
import com.sz.admin.dtuinfo.pojo.dto.DtuInfoCreateDTO;
import com.sz.admin.dtuinfo.pojo.dto.DtuInfoUpdateDTO;
import com.sz.admin.dtuinfo.pojo.dto.DtuInfoListDTO;
import com.sz.admin.dtuinfo.pojo.vo.DtuInfoVO;
import com.sz.core.common.entity.ImportExcelDTO;
import com.sz.core.common.enums.CommonResponseEnum;
import com.sz.core.util.CRC16Util;
import com.sz.admin.dtuinfo.pojo.po.DtuMessageLog;
import com.sz.admin.dtuinfo.service.DtuMessageLogService;
import com.sz.core.common.entity.LoginUser;
import com.sz.security.core.util.LoginUtils;
import jakarta.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * DTU信息表 Controller
 * </p>
 *
 * @author sz-admin
 * @since 2025-08-29
 */
@Tag(name =  "DTU信息表")
@RestController
@RequestMapping("dtu-info")
@RequiredArgsConstructor
public class DtuInfoController  {

    private final DtuInfoService dtuInfoService;
    private final DtuMessageLogService dtuMessageLogService;

    @Operation(summary = "新增")
    @SaCheckPermission(value = "dtu.info.create", orRole = GlobalConstant.SUPER_ROLE)
    @PostMapping
    public ApiResult<Void> create(@RequestBody DtuInfoCreateDTO dto) {
        dtuInfoService.create(dto);
        return ApiResult.success();
    }

    @Operation(summary = "修改")
    @SaCheckPermission(value = "dtu.info.update", orRole = GlobalConstant.SUPER_ROLE)
    @PutMapping
    public ApiResult<Void> update(@RequestBody DtuInfoUpdateDTO dto) {
        dtuInfoService.update(dto);
        return ApiResult.success();
    }

    @Operation(summary = "删除")
    @SaCheckPermission(value = "dtu.info.remove", orRole = GlobalConstant.SUPER_ROLE)
    @DeleteMapping
    public ApiResult<Void> remove(@RequestBody SelectIdsDTO dto) {
        dtuInfoService.remove(dto);
        return ApiResult.success();
    }

    @Operation(summary = "列表查询")
    @SaCheckPermission(value = "dtu.info.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping
    public ApiResult<PageResult<DtuInfoVO>> list(DtuInfoListDTO dto) {
        return ApiPageResult.success(dtuInfoService.page(dto));
    }

    @Operation(summary = "详情")
    @SaCheckPermission(value = "dtu.info.query_table", orRole = GlobalConstant.SUPER_ROLE)
    @GetMapping("/{id}")
    public ApiResult<DtuInfoVO> detail(@PathVariable Object id) {
        return ApiResult.success(dtuInfoService.detail(id));
    }

    @Operation(summary = "导入")
    @Parameters({
      @Parameter(name = "file", description = "上传文件", schema = @Schema(type = "string", format = "binary"), required = true),
    })
    @SaCheckPermission(value = "dtu.info.import")
    @PostMapping("/import")
    public void importExcel(@ModelAttribute ImportExcelDTO dto) {
        dtuInfoService.importExcel(dto);
    }

    @Operation(summary = "导出")
    @SaCheckPermission(value = "dtu.info.export")
    @PostMapping("/export")
    public void exportExcel(@RequestBody DtuInfoListDTO dto, HttpServletResponse response) {
        dtuInfoService.exportExcel(dto, response);
    }

    @Operation(summary = "发送数据")
    @SaCheckPermission(value = "dtu.info.send_data", orRole = GlobalConstant.SUPER_ROLE)
    @PostMapping("/send-data")
    public ApiResult<Void> sendData(@RequestBody Map<String, Object> request) {
        try {
            // Get the decimal value from request
            Long decimalValue = Long.valueOf(request.get("decimal").toString());
            String dtuId = request.get("dtuId").toString();

            // Convert decimal to hex string with padding
            String hexData = Long.toHexString(decimalValue).toUpperCase();
            if (hexData.length() % 2 != 0) {
                hexData = "0" + hexData;
            }
            // Pad to 4 characters (2 bytes) with leading zeros if needed
            while (hexData.length() < 4) {
                hexData = "00" + hexData;
            }

            // Create the full data string with fixed prefix
            String fullData = "00 06 01 34 " + hexData;

            // Remove spaces and convert to byte array
            String fullHexData = fullData.replace(" ", "");
            byte[] bytes = hexStringToByteArray(fullHexData);
            
            // Calculate CRC
            int crc = CRC16Util.calculateCRC16(bytes);
            String hexCrc = CRC16Util.toHexString(crc);

            // Reverse last 4 characters of hexCrc (e.g., "BFC9" -> "C9BF")
            String lastFour = hexCrc.substring(hexCrc.length() - 4);
            String reversed = lastFour.substring(2) + " " + lastFour.substring(0, 2);

            // Get port from DTU info
            DtuInfoVO dtuInfo = dtuInfoService.detail(dtuId);
            Integer port = dtuInfo.getPort();

            if (port == null) {
                return ApiResult.error(CommonResponseEnum.INVALID.message("DTU port not found"));
            }

            // Format the data to send: 00 06 01 34 00 c8 C9 BF
            String sendData = fullData + " " + reversed;
            String sendDataWithoutSpaces = sendData.replace(" ", "");

            // Convert hex string to byte array
            byte[] dataBytes = hexStringToByteArray(sendDataWithoutSpaces);

            // Send data via TCP
            try (Socket socket = new Socket("127.0.0.1", port)) {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(dataBytes);
                outputStream.flush();
            }

            // Log the message
            try {
                DtuMessageLog messageLog = new DtuMessageLog();
                messageLog.setDtuId(dtuId);
                messageLog.setText(decimalValue.toString());
                messageLog.setSeedMessage(hexCrc);
                messageLog.setCreateTime(LocalDateTime.now());
                
                // Get current user ID
                LoginUser loginUser = LoginUtils.getLoginUser();
                if (loginUser != null) {
                    messageLog.setCreateId(loginUser.getUserInfo().getId());
                }
                
                dtuMessageLogService.saveMessageLog(messageLog);
            } catch (Exception e) {
                // Log the error but don't fail the operation
                System.err.println("Failed to log message: " + e.getMessage());
            }

            return ApiResult.success();
        } catch (Exception e) {
            return ApiResult.error(CommonResponseEnum.INVALID.message("Error sending data: " + e.getMessage()));
        }
    }

    /**
     * Convert hex string to byte array
     *
     * @param hexString hex string
     * @return byte array
     */
    private static byte[] hexStringToByteArray(String hexString) {
        // Ensure even number of characters
        if (hexString.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex string must have an even number of characters");
        }

        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));
        }
        return data;
    }
}